package metrics

import (
	"fmt"
	"github.com/prometheus/client_golang/prometheus"
	"time"
)

// CreateExecutionTimerMetric 创建新的Histogram(直方图) HistogramVec 多个监控指标集合
func CreateExecutionTimerMetric(namespace string,help string)  *prometheus.HistogramVec {
	return prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Namespace: namespace,
			Name:      "Execution_latemcy_sconds",
			Help:      help,
			Buckets:   prometheus.ExponentialBuckets(0.01, 3, 10),
		}, []string{"path","step"})

}
// NewExecutionTimer 生成新的自定义结构体 ExecutionTimer
func NewExecutionTimer(histo *prometheus.HistogramVec,url string) *ExecutionTimer {
	now := time.Now()
	return &ExecutionTimer{
		histo: histo,
		start: now,
		last: now,
		path: url,
	}
}

// ObserveTotal 访问耗时
func(t *ExecutionTimer) ObserveTotal() {
	n := time.Now()
	d := time.Now().Sub(t.start).Seconds()
	fmt.Println(d,n,t.start,n.Sub(t.start))
	(*t.histo).WithLabelValues(t.path,"total").Observe(d)
}

// ObserveStep 距离上一次访问的时间间隔
func (t *ExecutionTimer) ObserveStep(step string) {
	now := time.Now()
	(*t.histo).WithLabelValues(t.path,step).Observe(now.Sub(t.last).Seconds())
	t.last = now
}
type ExecutionTimer struct {
	histo *prometheus.HistogramVec
	start time.Time
	last time.Time
	path string
}